package servlet.song;

import service.SongsService;
import service.impl.SongsServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

@WebServlet("/song/download")
public class DownloadServlet extends HttpServlet {

    private SongsService songsService = new SongsServiceImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Integer songId = Integer.valueOf(request.getParameter("id"));

        if (songId == null) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Song ID为空");
            return;
        }

        // 获取歌曲的下载链接
        String songPath = songsService.getSongPathById(songId);

        if (songPath == null) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND, "没找到歌曲");
            return;
        }

        // 使用 URL 类来处理远程链接
        try {
            URL songUrl = new URL(songPath);  // 获取到 URL 对象
            HttpURLConnection connection = (HttpURLConnection) songUrl.openConnection();
            connection.setRequestMethod("GET");
            connection.setDoInput(true);
            connection.connect();

            // 获取歌曲文件名
            String fileName = songUrl.getPath();
            fileName = fileName.substring(fileName.lastIndexOf("/") + 1);  // 只提取文件名

            String userAgent = request.getHeader("User-Agent");
            String downloadFileName = URLEncoder.encode(fileName, "UTF-8");
            if (userAgent != null && userAgent.contains("MSIE")) {
                downloadFileName = downloadFileName.replaceAll("\\+", "%20");
            }

            // 设置响应头，告诉浏览器这是一个下载文件
            response.setHeader("Content-Disposition", "attachment; filename=\"" + downloadFileName + "\"");
            response.setContentType("audio/mp3");

            // 从 URL 读取文件并写入响应流
            try (InputStream in = connection.getInputStream();
                 OutputStream out = response.getOutputStream()) {

                byte[] buffer = new byte[8192];
                int bytesRead;
                while ((bytesRead = in.read(buffer)) != -1) {
                    out.write(buffer, 0, bytesRead);
                }
            }
        } catch (MalformedURLException e) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "无效的歌曲链接");
        } catch (IOException e) {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "下载文件时发生错误");
        }
    }
}

